package br.ufrj.ppgi.infovis.util;

import org.mt4j.util.MTColor;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;

import br.ufrj.ppgi.infovis.mtgraph.Graph;
import br.ufrj.ppgi.infovis.mtgraph.GraphEdgeManager;
import br.ufrj.ppgi.infovis.mtgraph.GraphNode;
import br.ufrj.ppgi.infovis.mtgraph.GraphScene;

public class XMLImport { 

	
	private GraphScene scene;
	private String pathName;
	
	public XMLImport(GraphScene scene, String path){
		this.scene = scene;
		this.pathName = path;
	}
	
	//importa v�rtices
	public Graph Import() {
		Graph graph = new Graph();
		graph.setGraphScene(this.scene);

		try {
			System.out.println("Pathname import xml : "+this.pathName);
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(this.pathName);

			Element elem = doc.getDocumentElement();
			NodeList nl= elem.getElementsByTagName("node");
			int l = nl.getLength();

			for( int i=0; i<l; i++ ) {  
				Element tagVertice = (Element) nl.item( i );  

				String id = tagVertice.getAttribute("id");
				String type = tagVertice.getAttribute("type");
				NodeList tagTxt = tagVertice.getElementsByTagName("label");
				String txt = tagTxt.item(0).getTextContent();
				
				GraphNode node = new GraphNode();
				node.setId(id);
				node.setGraph(graph);
				node.setLabel(txt);
				node.setType(type);
				MTColor nodeColor = scene.getConfig().getColorByCategoryName(type);
				node.setColor(nodeColor);
				
				graph.addNode(node);
				
			}  
			
			nl = elem.getElementsByTagName("edge");
			l = nl.getLength();
			
			for (int i = 0; i < l; i++) {
				Element edgeElement = (Element) nl.item( i );
				
				String strNodeA = edgeElement.getAttribute("a");
				String strNodeB = edgeElement.getAttribute("b");
				
				GraphEdgeManager.makeGraphEdge(graph.getNodeById(strNodeA), 
						graph.getNodeById(strNodeB));
			}

		} catch (SAXException e) {
			Exception x = e.getException ();
			((x == null) ? e : x).printStackTrace ();

		} catch (Throwable t) {
			t.printStackTrace ();
		}
		return graph;
	}
	

}
